package xjtu.se.articlecommunity.user.info;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import xjtu.se.articlecommunity.common.*;
import xjtu.se.articlecommunity.common.dto.CurrentUser;
import xjtu.se.articlecommunity.user.info.dao.UInfoDao;
import xjtu.se.articlecommunity.user.info.dto.CUserTab;
import xjtu.se.articlecommunity.user.info.dto.MyDto;
import xjtu.se.articlecommunity.user.info.dto.UserDetail;
import xjtu.se.articlecommunity.user.info.dto.UserInfoDto;
import xjtu.se.articlecommunity.user.info.impl.UInfoService;
import xjtu.se.articlecommunity.user.login.dto.CodeLoginDto;
import xjtu.se.articlecommunity.user.login.dto.TelLoginDto;

import javax.annotation.Resource;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/user/information")
public class InformationAPI {
    @Resource
    UInfoService uInfoService;
    @Resource
    CommonService commonService;
    @Resource
    MailService mailService;
    @Resource
    SMSService smsService;
    @Resource
    CacheService cacheService;
    @Resource
    UInfoDao uInfoDao;


    @GetMapping("/userinfo")
    public Result getInfo(@RequestHeader("Token") String token,@RequestParam("u_id") String u_id) {
        //CurrentUser currentUser = TokenUtils.getUserInfo(token, commonService);
        UserInfoDto userDto= uInfoDao.finduser(u_id);
        return Result.success(userDto);
    }

    @GetMapping("/usertab")
    public Result getDetail(@RequestParam("u_id") String u_id) {
        List<CUserTab> list = uInfoDao.findUsertabs(u_id);
        return Result.success(list);
    }
    @GetMapping("/userdetail")
    public Result getUserTab(@RequestParam("u_id") String u_id) {
        UserDetail userDto= uInfoDao.finduserDetail(u_id);
        return Result.success(userDto);
    }

    @GetMapping("/mytelmail")
    public Result getTelAndMail(@RequestHeader("Token") String token) {
        CurrentUser currentUser = TokenUtils.getUserInfo(token, commonService);
        MyDto userDto= uInfoDao.getTelMail(currentUser.getU_id());
        String tel = userDto.getU_tel();
        if(tel!=null) userDto.setU_tel(tel.substring(0,3)+"****"+tel.substring(7,11));

        String mail = userDto.getU_mail();
        if(mail!=null) userDto.setU_mail(mail.substring(0,3)+"****@*****");

        return Result.success(userDto);
    }

    @PostMapping("/changeInfo")
    public Result changeInfo(@RequestHeader("Token") String token,@RequestBody UserDetail userDto){
        CurrentUser currentUser = TokenUtils.getUserInfo(token, commonService);
        userDto.setU_id(currentUser.getU_id());

        log.info(userDto.toString());
        uInfoDao.ChangeInfo(userDto);
        return Result.success();
    }

    @RequestMapping("/checkByPw")
    public Result checkByPw(@RequestParam("passwd") String passwd,@RequestHeader("Token") String token){
        CurrentUser currentUser = TokenUtils.getUserInfo(token, commonService);
        if (uInfoDao.checkPassword(currentUser.getU_id()).equals(passwd)){
            return Result.success();
        }
        return Result.fail(Result.ERR_CODE_BUSINESS,"密码错误，身份验证失败！");
    }

    //发送验证码以验证用户身份
    @GetMapping("/telcodeForCheck")
    public Result telcode(@RequestHeader("Token") String token) {
        CurrentUser currentUser = TokenUtils.getUserInfo(token, commonService);
        String tel=uInfoDao.findtel(currentUser.getU_id()); //获取当前用户手机号
        log.info(tel);
        String telcode = smsService.sendVerificationCode(tel);
        log.info(telcode);
        cacheService.saveVerificationCode(tel, telcode);
        return Result.success();
    }
    //手机验证用户身份
    @RequestMapping("/checkBytel")
    public Result checkBytel(@RequestHeader("Token") String token,@RequestParam("telcode") String telcode){
        log.info(telcode);
        CurrentUser currentUser = TokenUtils.getUserInfo(token, commonService);
        String tel=uInfoDao.findtel(currentUser.getU_id());
        if (cacheService.findVerificationCode(tel).equals(telcode)){
            return Result.success();
        }
        return Result.fail(Result.ERR_CODE_BUSINESS,"验证码错误");
    }
    //验证新手机
    @GetMapping("/telcode")
    public Result newtelcode(@RequestParam("tel") String tel) {
        log.info(tel);
        String telcode = smsService.sendVerificationCode(tel);
        log.info(telcode);
        cacheService.saveVerificationCode(tel, telcode);
        return Result.success();
    }
    //修改手机
    @PostMapping("/changetel")
    public Result changetel(@RequestBody TelLoginDto dto, @RequestHeader("Token") String token){
        if (cacheService.findVerificationCode(dto.getTel()).equals(dto.getTelcode())){
            CurrentUser currentUser = TokenUtils.getUserInfo(token, commonService);
            uInfoDao.Changetel(currentUser.getU_id(),dto.getTel());
            return Result.success();
        }else {
            return Result.fail(500,"验证码错误！");
        }
    }


    //发送验证码以验证用户身份
    @GetMapping("/mailcodeForCheck")
    public Result mailcode(@RequestHeader("Token") String token) {
        CurrentUser currentUser = TokenUtils.getUserInfo(token, commonService);
        String mail=uInfoDao.findmail(currentUser.getU_id()); //获取当前用户邮箱
        log.info(mail);
        String mailcode = mailService.sendCode(mail);
        log.info(mailcode);
        cacheService.saveVerificationCode(mail, mailcode);
        return Result.success();
    }
    //邮箱验证用户身份
    @RequestMapping("/checkByMail")
    public Result checkByMail(@RequestHeader("Token") String token,@RequestParam("mailcode") String mailcode){
        log.info(mailcode);
        CurrentUser currentUser = TokenUtils.getUserInfo(token, commonService);
        String mail=uInfoDao.findmail(currentUser.getU_id());
        if (cacheService.findVerificationCode(mail).equals(mailcode)){
            return Result.success();
        }
        return Result.fail(Result.ERR_CODE_BUSINESS,"验证码错误");
    }
    //验证新邮箱
    @GetMapping("/mailcode")
    public Result newmailcode(@RequestParam("mail") String mail) {
        log.info(mail);
        String mailcode = mailService.sendCode(mail);
        log.info(mailcode);
        cacheService.saveVerificationCode(mail, mailcode);
        return Result.success();
    }
    //修改邮箱
    @PostMapping("/changemail")
    public Result changeMail(@RequestBody CodeLoginDto dto, @RequestHeader("Token") String token){
        if (cacheService.findVerificationCode(dto.getMail()).equals(dto.getMailcode())){
            CurrentUser currentUser = TokenUtils.getUserInfo(token, commonService);
            uInfoDao.ChangeMail(currentUser.getU_id(),dto.getMail());
            return Result.success();
        }else {
            return Result.fail(500,"验证码错误！");
        }
    }

    //修改密码
    @PostMapping("/changePasswd")
    public Result changePw(@RequestParam("passwd") String passwd,@RequestHeader("Token") String token){
        CurrentUser currentUser = TokenUtils.getUserInfo(token, commonService);
        uInfoDao.ChangePasswd(currentUser.getU_id(),passwd);
        return Result.success();
    }

    @PostMapping("/avatar")
    public Result uploadAvaor(MultipartFile avatar, @RequestHeader("Token") String token) throws IOException {

        InputStream in = avatar.getInputStream();

        String name = UUID.randomUUID().toString();//获得通过uuid算法得到的不重复的字符串
        String submitedFilename = avatar.getOriginalFilename();//原始文件名
        String suffix = submitedFilename.substring(submitedFilename.lastIndexOf("."));
        String filename = name + suffix;
        OutputStream out = new FileOutputStream("E://avatar/" + filename);

        byte[] b = new byte[10240];//容量为10240字节的缓存区
        int len = -1;//从输入流读取并放入缓存区的数据量

        while ((len = in.read(b)) != -1) {
            out.write(b, 0, len);
        }
        out.flush();
        out.close();
        in.close();

        CurrentUser currentUser = TokenUtils.getUserInfo(token,commonService);
        uInfoService.setUserAvatar(currentUser.getU_id(),filename);
        return Result.success();
    }

}
